package com.itheima.service.impl;

import cn.itheima.health.entity.QueryPageBean;
import cn.itheima.health.resources.RedisConstant;
import cn.itheima.health.service.SetmealService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {


@Autowired
    private SetmealMapper setmealMapper;


@Autowired
private   CheckGroupMapper checkGroupMapper;

@Autowired
private   CheckItemMapper checkItemMapper;

/*@Autowired
    private JedisPool jedisPool;*/

@Autowired
private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //   检查组 添加一条记录  返回主键    中间表需要
        setmealMapper.add(setmeal);  //  Mybatis 主键 注入  实体类属性id

        Integer setmealId = setmeal.getId();  //  新增记录主键

        if(checkgroupIds!=null){
            //  循环更新中间表
            for (Integer gid : checkgroupIds) {
                setmealMapper.addCheckGroupAndSetMeal(setmealId,gid);
            }

        }

        //  图片存储 redis
        redisTemplate.opsForValue().set(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        /*Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        jedis.close();*/
    }



    @Override
    public Map findPage(QueryPageBean queryPageBean) {
        Map map  = new HashMap();
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Setmeal> list  = setmealMapper.findPage(queryPageBean.getQueryString());
        PageInfo<Setmeal> pageInfo = new PageInfo<Setmeal>(list);
        map.put("list",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        return map;
    }

    /**

     *新思路:<br/>
     *      请求过来先从缓存中取出存储的套餐列表数据<br/>
     *      <ul>
     *          <li>缓存内取出数据不为空: 直接将数据封装到Result同一响应结果集内,返回给前端</li>
     *          <li>缓存内取出数据为空: 1.先从数据库内查出列表数据;2.将列表数据放入redis中(以String类型存储,name为SETMEAL_LIST,值为json类型)</li>
     *      </ul>
     * @return String 返回Json字符串
     * @author wuguang
     * @date 2020/8/5 20:41
     *
     */
    @Override
    public String findAll() {
        //从redis内取出数据:
        /*Jedis jedis = jedisPool.getResource();
        String setMealListStr = jedis.get("SETMEAL_LIST");*/
        String setMealListStr = (String) redisTemplate.opsForValue().get("SETMEAL_LIST");

        if(setMealListStr==null||setMealListStr.length()==0||setMealListStr.equals("")){
            //redis内没有数据,从数据库内查询
            List<Setmeal> setmealList = setmealMapper.findAll();
            //将查到的数据放到redis内以JSON格式
            setMealListStr = JSON.toJSONString(setmealList);

           /* jedis.set("SETMEAL_LIST",setMealListStr);
            jedis.close();*/
           redisTemplate.opsForValue().set("SETMEAL_LIST",setMealListStr);

            System.out.println("从数据库内取");
            return setMealListStr;
        }
        System.out.println("从redis内取");
        return setMealListStr;
    }

    /**
     * @param id 将要查询的套餐的id
     * @return java.lang.String 返回Json字符串
     * @author wuguang
     * @date 2020/8/5 21:58
     *
     */
    @Override
    public String findSetMealDetail(Integer id) {
        //从redis中查询有没有
        /*Jedis resource = jedisPool.getResource();
        String setMealDetailJson = resource.hget("SETMEAL_DETAIL","SETMEAL_DETAIL"+"_"+id);*/

        String setMealDetailJson = (String) redisTemplate.opsForHash().get("SETMEAL_DETAIL", "SETMEAL_DETAIL_" + id);


        //判断
        if(setMealDetailJson==null||setMealDetailJson.length()==0||setMealDetailJson.equals("")){
            //如果redis内没有
            //  1  查询套餐基本信息
            Setmeal setmeal = setmealMapper.findSetMealById(id);

            //将简单的setMeal对象 存入Hsah数据结构中,用于跳转预约页面时使用
            String simpleSetMeal = JSON.toJSONString(setmeal);

            redisTemplate.opsForHash().put("SIMPLE_SETMEAL_DETAIL","SIMPLE_SETMEAL_DETAIL_"+id,simpleSetMeal);
            //resource.hset("SIMPLE_SETMEAL_DETAIL","SIMPLE_SETMEAL_DETAIL"+"_"+id,simpleSetMeal);

            //  2  根据套餐id  查询 对应检查组信息   没有对应检查项信息
            List<CheckGroup>  checkGroupList = checkGroupMapper.findCheckGroupsBySetMealId(id);

            //  3 通过检查组id  查询 对应 检查项的信息
            if(checkGroupList!=null){
                for (CheckGroup checkGroup : checkGroupList) {

                    List<CheckItem>  checkItemList =  checkItemMapper.findCheckItemsByCheckGroupId(checkGroup.getId());

                    checkGroup.setCheckItems(checkItemList);//  封装每一个检查组 对应检查项信息
                }
            }

            //套餐对应的检查组和检查项信息 都封装到 套餐
            setmeal.setCheckGroups(checkGroupList);
            //转化为json对象
            setMealDetailJson = JSON.toJSONString(setmeal);

            //存入hash结构
           /* resource.hset("SETMEAL_DETAIL","SETMEAL_DETAIL"+"_"+id,setMealDetailJson);
            resource.close();*/
           redisTemplate.opsForHash().put("SETMEAL_DETAIL","SETMEAL_DETAIL_"+id,setMealDetailJson);

            System.out.println("从数据库内取");
            return setMealDetailJson;
        }

       /* resource.close();*/
        System.out.println("从redis查询");
        return setMealDetailJson;
    }

    /**
     *
     *  先前在查询订单信息的时候已经在查询检查组集合之前就将简单的,<br/>
     *  不包含集合内容的套餐对象放到了redis内,以hash结构存储,name=SIMPLE_SETMEAL_DETAIL
     *  每个entry的键是"SIMPLE_SETMEAL_DETAIL"+"_"+id形式拼接的
     *
     * @param id 前台传递过来的套餐的id
     * @return java.lang.String
     * @author wuguang
     * @date 2020/8/5 22:29
     *
     */

    @Override
    public String findSetMealById(Integer id) {

        //1.先从redis内找
       /* Jedis resource = jedisPool.getResource();
        String simpleSetmealDetail = resource.hget("SIMPLE_SETMEAL_DETAIL", "SIMPLE_SETMEAL_DETAIL" + "_" + id);*/
        String simpleSetmealDetail = (String) redisTemplate.opsForHash().get("SIMPLE_SETMEAL_DETAIL", "SIMPLE_SETMEAL_DETAIL_" + id);
        //2.判断
        if(simpleSetmealDetail==null||simpleSetmealDetail.length()==0||simpleSetmealDetail.equals("")){
            //redis内没有数据,从数据库内找
            Setmeal simpleSetMealById = setmealMapper.findSetMealById(id);

            //转化为json格式
            simpleSetmealDetail = JSON.toJSONString(simpleSetMealById);

           /* //存入redis
            resource.hset("SIMPLE_SETMEAL_DETAIL","SIMPLE_SETMEAL_DETAIL" + "_" + id,simpleSetmealDetail);

            //关闭资源
            resource.close();*/

           redisTemplate.opsForHash().put("SIMPLE_SETMEAL_DETAIL","SIMPLE_SETMEAL_DETAIL_" + id,simpleSetmealDetail);
            System.out.println("从数据库取的: SIMPLE_SETMEAL_DETAIL" + "_" + id);

            return simpleSetmealDetail;

        }

      /*  resource.close();*/
        System.out.println("从redis取的: SIMPLE_SETMEAL_DETAIL" + "_" + id);
        return simpleSetmealDetail;
    }

    //    @Override
//    public Map findCheckitemsByGroupId(Integer id) {
//        Map map = new HashMap();
//        List<CheckItem> list = checkItemMapper.findAll();
//        Integer [] checkitems  = checkGroupMapper.findCheckitemsByGroupId(id);
//        map.put("list",list);
//        map.put("checkitems",checkitems);
//        return map;
//    }
//
//    @Override
//    public void edit(CheckGroup checkGroup, Integer[] checkitems) {
//
//        //  检查组信息修改  update  t_checkgroup  set  xxx where  id = #{id}
//
//        checkGroupMapper.edit(checkGroup);
//
//
//        Integer checkGroupId = checkGroup.getId();  // 检查组的id
//        //  1 先接触关系  删除中间表数据   根据 检查组id
//        checkGroupMapper.removeCheckItemsByGroupId(checkGroupId);
//
//        if(checkitems!=null){
//            //  循环更新中间表
//            for (Integer checkitemid : checkitems) {
//                checkGroupMapper.addCheckGroupAndCheckItems(checkGroupId,checkitemid);
//            }
//
//        }
//
//    }
//
//    @Override
//    public List<CheckGroup> findAll() {
//        return checkGroupMapper.findAll();
//    }
}











